<template>
  <div>
    <el-input v-model="batchName" placeholder="请输入批次名"></el-input>
    <el-upload
      ref="uploadRef"
      style="margin-top: 20px"
      multiple
      :action="uploadUrl"
      :file-list="fileList"
      :before-upload="beforeUpload"
      :on-success="handleSuccess"
      :on-error="handleError"
      :headers="headers"
      :auto-upload="false"
      list-type="text"
      name="files"
    >
      <el-button type="primary">选择文件</el-button>
    </el-upload>
  </div>
</template>

<script setup>
import { ref } from "vue";
import axios from "axios"; // 确保安装了 axios

const uploadRef = ref(null);
const uploadUrl = import.meta.env.VITE_APP_BASE_API + "/file/import/upload"; // 替换为你的上传地址
const headers = {
  /* 你的请求头，如认证信息等 */
};
const batchName = ref("");
const fileList = ref([]);

const beforeUpload = (file) => {
  const isExcel =
    file.type === "application/vnd.ms-excel" ||
    file.type ===
      "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
  if (!isExcel) {
    alert("只能上传 Excel 文件!");
    return false;
  }
  return true;
};

const handleSuccess = (response, file, fileList) => {
  // 处理上传成功的回调
};

const handleError = (err, file, fileList) => {
  // 处理上传失败的回调
};

const submitUpload = async () => {
  if (fileList.value.length === 0) {
    alert("请先选择文件");
    return;
  }

  const formData = new FormData();
  fileList.value.forEach((file) => {
    formData.append("files", file.raw); // 'files' 是后端接收的字段名
  });
  formData.append("batchName", batchName.value);

  try {
    const response = await axios.post(uploadUrl, formData, { headers });
    // 处理上传成功
    console.log("上传成功:", response);
  } catch (error) {
    // 处理上传失败
    console.error("上传失败:", error);
  }
};
</script>
